﻿
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 泛型观察者基类
/// </summary>
/// <typeparam name="T">类对象</typeparam>
/// <typeparam name="P">委托参数</typeparam>
/// <typeparam name="K">字典Key</typeparam>
public class DispatcherBase<T, P, K> :Singleton<DispatcherBase<T, P, K>>, IDisposable where T:new() where P :class
{
    public delegate void Handler(P obj);
    private Dictionary<K,List<Handler>> mDicListHandler=new Dictionary<K, List<Handler>>();
    /// <summary>
    /// 添加事件监听
    /// </summary>
    /// <param name="key"></param>
    /// <param name="handler"></param>
    public void AddEventListener(K key,Handler handler)
    {
        if (mDicListHandler.ContainsKey(key))
        {
            mDicListHandler[key].Add(handler);
        }
        else
        {
            mDicListHandler[key] = new List<Handler>();
            mDicListHandler[key].Add(handler);
        }
    }
    /// <summary>
    /// 移除事件监听
    /// </summary>
    /// <param name="key"></param>
    /// <param name="handler"></param>
    public void RemoveEventListener(K key,Handler handler)
    {
        if (mDicListHandler.ContainsKey(key))
        {
            if (mDicListHandler[key].Contains(handler))
            {
                mDicListHandler[key].Remove(handler);
            }
        }
    }
    /// <summary>
    /// 执行监听的事件(有参数时)
    /// </summary>
    /// <param name="key"></param>
    /// <param name="param"></param>
    public void DispatchEvent(K key, P param)
    {
        if (mDicListHandler.ContainsKey(key))
        {
            if (mDicListHandler[key] != null)
            {
                for (int i = 0; i < mDicListHandler[key].Count; i++)
                {
                    mDicListHandler[key][i](param);
                }
            }
        }
    }
    /// <summary>
    /// 执行监听的事件(无参数时)
    /// </summary>
    /// <param name="key"></param>
    /// <param name="param"></param>
    public void DispatchEvent(K key)
    {
        DispatchEvent(key,null);
    }

    public void Dispose()
    {
        
    }
}
